package com.liao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liao.domain.LoginUser;
import com.liao.mapper.MovieRoleMapper;
import com.liao.mapper.MovieUsersMapper;
import com.liao.model.po.MovieUsers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private MovieUsersMapper userMapper;


    @Autowired
    private MovieRoleMapper movieRoleMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        LambdaQueryWrapper<MovieUsers> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MovieUsers::getUsername, username);
        MovieUsers user = userMapper.selectOne(queryWrapper);
        // 如果没有查询到用户则抛出异常,在过滤链中有异常捕获，这里抛出的异常会被捕获
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或密码错误");
        }

//         查询对应的权限信息
        List<String> list = movieRoleMapper.selectPermsByUserId(Long.valueOf(user.getId()));

//         把数据封装成UserDetails返回
        return new LoginUser(user, list);

    }


    }
